package com.xiaobai.mall.wrapper.autoconfigure;

import com.xiaobai.mall.common.domain.Result;
import com.xiaobai.mall.common.enums.ResponseCode;
import com.xiaobai.mall.common.exception.SessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = Controller.class)
public class ExceptionHandlerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    /**
     * 校验异常
     */
    @ExceptionHandler(value = {IllegalArgumentException.class, IllegalStateException.class})
    @ResponseBody
    public Result<Object> paramValidateExceptionHandler(Exception e) {
        logger.error(ResponseCode.VALIDATE_ERROR.getDesc(), e);
        return Result.buildErrorResult(ResponseCode.VALIDATE_ERROR, e.getMessage());
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = {SessionException.class})
    @ResponseBody
    public Result<Object> sessionException(SessionException e) {
        logger.error(ResponseCode.SESSION_ERROR.getDesc(), e);
        return Result.buildErrorResult(ResponseCode.SESSION_ERROR, e.getMessage());
    }

    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> commonExceptionHandler(Exception e) {
        logger.error(ResponseCode.BUSINESS_ERROR.getDesc(), e);
        return Result.buildErrorResult(ResponseCode.BUSINESS_ERROR, e.getMessage());
    }

}
